package com.nulldev.util.net.packets.p2pc;

import com.nulldev.util.crypto.api2.EncryptionUtil;
import com.nulldev.util.crypto.api2.EncryptionUtil.Types;
import com.nulldev.util.crypto.encryptAPI.manage.EncryptAPI;
import com.nulldev.util.net.packets.APILevel;
import com.nulldev.util.net.packets.NetInfo;
import com.nulldev.util.net.packets.NetPacket;
import com.nulldev.util.net.packets.PacketManager;
import com.nulldev.util.string.StringsUtil;

@APILevel(level = 1)
@Deprecated
/**
 * Replaced by nCrypt API in nullUtil 2.6
 * @since nullUtil 2.0 / nPacket 1.0
 * @author null
 *
 */
public class P2PCRequestKey extends NetPacket{

	public P2PCRequestKey() {
		super("P2PC: Request Key", "p2pc.key", "request.key");
	}

	@Override
	public void client(byte[] data, byte[] raw, final NetInfo client) {
	}

	@Override
	public void server(byte[] data0, byte[] raw, final NetInfo connection) {
		final String data = createString(data0);
		final boolean extendedMode = data.contains("[ext=1]");
		final boolean shortMode = data.contains("[short=1]");
		if (extendedMode) {
			final NetInfo core = connection;
			final String dkey = core.format();
			final String rnd = StringsUtil.generateSecure(128);
			final String key = EncryptAPI.getEncryptorByID("encryptAPI.XXTEA").encrypt(rnd, dkey); //EncryptionUtil.byType(Types.P2PE2_COMPRESS).encrypt(rnd, dkey);
			core.setKey(rnd);
			core.sendBlocking(PacketManager.fromID("p2pc.setKey", key));
		}else if (shortMode) {
			final NetInfo core = connection;
			final String dkey = core.format();
			final String rnd = StringsUtil.generateSecure(64);
			final String key = EncryptAPI.getEncryptorByID("encryptAPI.XXTEA").encrypt(rnd, dkey); //EncryptionUtil.byType(Types.P2PE2_COMPRESS).encrypt(rnd, dkey);
			core.setKey(rnd);
			core.sendBlocking(PacketManager.fromID("p2pc.setKey", key));
		}else {
			final NetInfo core = connection;
			final String dkey = core.format();
			final String rnd = StringsUtil.generateSecure(32);
			final String key = EncryptAPI.getEncryptorByID("encryptAPI.XXTEA").encrypt(rnd, dkey); //EncryptionUtil.byType(Types.P2PE2_COMPRESS).encrypt(rnd, dkey);
			core.setKey(rnd);
			core.sendBlocking(PacketManager.fromID("p2pc.setKey", key));
		}
	}

}
